package com.bjgraphite.report.advice;

import com.alibaba.fastjson2.JSON;
import com.bjgraphite.report.enums.BizErrorCode;
import com.bjgraphite.report.exception.BaseException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhouxiaolong
 * @version V1.0
 * @Description: 全局异常处理
 * @date 2018/4/19 15:30
 */
@RestControllerAdvice
public class GlobalExceptionAdvice {

    private static final Log logger = LogFactory.getLog(GlobalExceptionAdvice.class);


    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus
    public Map<String, Object> handlerRunTimeException(HttpServletRequest request, RuntimeException exception) {
        //记录日志
        handleLog(request, exception, null);
        Map<String, Object> resultMap = new HashMap<String, Object>(2);
        String message = BizErrorCode.SYSTEM_BUSY_ERROR.getMessage();
        resultMap.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
        resultMap.put("message", message);
        return resultMap;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> handlerException(HttpServletRequest request, Exception exception) {
        //记录日志
        handleLog(request, exception, null);
        Map<String, Object> resultMap = new HashMap<String, Object>(2);
        int code = HttpStatus.INTERNAL_SERVER_ERROR.value();
        String message = BizErrorCode.SYSTEM_BUSY_ERROR.getMessage();
        if (exception instanceof BaseException) {
            BaseException baseException = (BaseException) exception;
            code = baseException.getBizErrorCode().getCode();
            message = baseException.getBizErrorCode().getMessage();
            Object[] params = baseException.getParams();
            /*if (params != null && params.length > 0) {
                message = MessageHelper.getMessage(baseException.getBizErrorCode(), params);
            }*/


        }
        resultMap.put("code", code);
        resultMap.put("message", message);
        return resultMap;
    }

    @ExceptionHandler({BaseException.class})
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public Map<String, Object> handlerBaseException(HttpServletRequest request, BaseException exception) {
        //记录日志
        handleLog(request, exception, null);
        Map<String, Object> resultMap = new HashMap<String, Object>(2);
        String message = exception.getBizErrorCode().getMessage();
        Object[] params = exception.getParams();
        if (params != null && params.length > 0) {
            //message = MessageHelper.getMessage(exception.getBizErrorCode(), params);
        }
        resultMap.put("code", exception.getBizErrorCode().getCode());
        resultMap.put("message", message);

        /*if(StringUtils.isNotBlank(exception.getMessage())){
            resultMap.put("message",exception.getMessage());
        }*/
        return resultMap;
    }


    private void handleLog(HttpServletRequest request, Exception ex, String requestBody) {
        StringBuffer logBuffer = new StringBuffer();
        if (request != null) {
            logBuffer.append(" \r\n request method=" + request.getMethod());
            logBuffer.append(" \r\n url=" + request.getRequestURL());
        }

        // 请求体参数
        if (StringUtils.isNotBlank(requestBody)) {
            logBuffer.append(" \r\n requestBody:" + requestBody);
        }

        if (ex != null) {
            logBuffer.append("\r\n ======= exception start:");
            logBuffer.append("\r\n ======= exception:" + ex);
            StackTraceElement[] trace = ex.getStackTrace();
            for (StackTraceElement traceElement : trace) {
                logBuffer.append("\r\n" + traceElement);
            }

        }

        Map<String, String[]> parameterMap = request.getParameterMap();
        if (parameterMap != null && parameterMap.size() > 0) {
            logBuffer.append("params:" + JSON.toJSONString(request.getParameterMap()));
        }

        logBuffer.append("\r\n ======= exception end");
        logger.error(logBuffer.toString(), ex);
        logger.error(ex);
    }
}
